import React, { useState } from 'react';
import { Modal, Radio, Button, Typography, Tag, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { useSelector, useDispatch } from 'react-redux';
import { RootState, AppDispatch } from '../../store';
import { setCurrentEntity } from '../../store/slices/merchant';
import { switchMerchantIdentity } from '../../api/merchant';
import './index.less';

const { Text } = Typography;

interface MerchantIdentitySwitcherProps {
  visible: boolean;
  onClose: () => void;
}

const MerchantIdentitySwitcher: React.FC<MerchantIdentitySwitcherProps> = ({ visible, onClose }) => {
  const dispatch = useDispatch<AppDispatch>();
  const { currentEntity, list } = useSelector((state: RootState) => state.merchant);
  const [selectedValue, setSelectedValue] = useState<string>('');
  const [loading, setLoading] = useState(false);

  // 按类别分组身份列表
  const groupedIdentities = list.reduce((acc, identity) => {
    let category = '其他';
    if (identity.entity_type === 1) {
      category = '企业身份';
    } else if (identity.entity_type === 2) {
      category = '管理员身份';
    }
    
    if (!acc[category]) {
      acc[category] = [];
    }
    acc[category].push(identity);
    return acc;
  }, {} as Record<string, typeof list>);

  // 处理身份切换
  const handleIdentityChange = (value: string) => {
    setSelectedValue(value);
  };

  // 初始化选中值
  React.useEffect(() => {
    if (currentEntity) {
      setSelectedValue(currentEntity.id.toString());
    }
  }, [currentEntity, visible]);

  // 确认切换
  const handleConfirm = async () => {
    if (selectedValue) {
      const selectedEntity = list.find(item => item.id.toString() === selectedValue);
      if (selectedEntity) {
        setLoading(true);
        try {
          const response = await switchMerchantIdentity(selectedEntity.id);
          console.log('身份切换响应:', response);
          
          // 更新当前选中的实体
          if (response && response.current_entity) {
            dispatch(setCurrentEntity(response.current_entity));
            
            // 同时存储到localStorage
            localStorage.setItem('currentMerchantEntity', JSON.stringify(response.current_entity));
          }
          
          message.success(response.message || `已切换到: ${selectedEntity.entity_name}`);
          onClose();
        } catch (error) {
          console.error('身份切换失败:', error);
          message.error('身份切换失败，请重试');
        } finally {
          setLoading(false);
        }
      }
    }
  };

  // 添加新身份
  const handleAddIdentity = () => {
    message.info('添加新身份功能待开发');
  };

  return (
    <Modal
      title="切换身份"
      open={visible}
      onCancel={onClose}
      footer={null}
      width={400}
      className="merchant-identity-modal"
    >
      <div className="identity-switcher">
        <div className="summary">
          <Text type="secondary">管理 {list.length} 个身份</Text>
        </div>
        
        <div className="identity-list">
          <Radio.Group 
            value={selectedValue || currentEntity?.id} 
            onChange={(e) => handleIdentityChange(e.target.value)}
            className="identity-radio-group"
          >
            {Object.entries(groupedIdentities).map(([category, identities]) => (
              <div key={category} className="identity-category">
                <div className="category-title">
                  <Text strong>{category} ({identities.length})</Text>
                </div>
                
                {identities.map((identity) => (
                  <div key={identity.id} className="identity-item">
                    <Radio value={identity.id.toString()} className="identity-radio">
                      <div className="identity-content">
                        <div className="identity-name">
                          {identity.entity_name}
                          {identity.status === 1 && (
                            <Tag color="green">已认证</Tag>
                          )}
                        </div>
                        {identity.description && (
                          <div className="identity-description">
                            {identity.description}
                          </div>
                        )}
                      </div>
                    </Radio>
                  </div>
                ))}
              </div>
            ))}
          </Radio.Group>
        </div>
        
        <div className="actions">
          <Button 
            type="dashed" 
            icon={<PlusOutlined />} 
            onClick={handleAddIdentity}
            className="add-identity-btn"
          >
            添加新身份
          </Button>
          
          <div className="confirm-actions">
            <Button onClick={onClose} disabled={loading}>取消</Button>
            <Button type="primary" onClick={handleConfirm} loading={loading}>
              确认切换
            </Button>
          </div>
        </div>
      </div>
    </Modal>
  );
};

export default MerchantIdentitySwitcher;
